<?php             
class User_right extends MY_Controller{				
	function __construct()
	{
		parent::__construct();
	}
	function _remap($method,$params = array())
	{
	   $this->_admin_remap($method,$params,basename(dirname(__FILE__)));	   
	}
        
    function index(){    	
			$user_id = $this->input->get('id');
    		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    			if(empty($user_id))
					die('Sorry, You can not do this!');	
    			else 
    				$this->load->view('admin/user_right/right_list',array('user_id'=>$user_id));
   			}else{
    			if(empty($user_id))
					header('location: /admin/accounts');	
    			else 
	    			$this->_setLayout('admin/user_right/right_list','admin_layout',array('user_id'=>$user_id));
    		}
    }
         
	public function load_user_permission(){
		$userId = $this->input->get('user_id');
		
        $this->load->model('Key_model');
        $rsPermissionKeyByUser = $this->Key_model->getPermissionKeyByUser($userId);
        $permissionKeyByUser = array();
        foreach($rsPermissionKeyByUser as $row){
        	$permissionKeyByUser[] = $row['id'];
        }
		
		
		$sWhere = "";
		if ( $_GET['sSearch'] != "" )
		{
			$sWhere = "key_name LIKE '%".$_GET['sSearch']."%'";
		}
		//$listPermissionKey = $this->Key_model->get_list($_GET['iDisplayStart'],$_GET['iDisplayLength'],$this->fnColumnToField( $_GET['iSortCol_0'] ),$_GET['sSortDir_0'],$sWhere);		
		$listPermissionKey = $this->Key_model->get_list(null,null,$this->fnColumnToField( $_GET['iSortCol_0'] ),$_GET['sSortDir_0'],$sWhere);
		$listCategory = array();
		foreach($listPermissionKey as $key=>$value){
			$cur_cat = trim($value['category']);
			$listCategory[$cur_cat][] = $value;
		}
		
		
		$resultArr = array();
		$i = 0;
		foreach ($listCategory as $category=>$listKey){
			$k = $i;
			$category = trim($category);
			$class = str_replace(' ', '-', strtolower($category));
			$flag = true;
			foreach($listKey as $key=>$value){
				$i+=1;
				//$checkStr = (in_array($value['id'],$permissionKeyByUser))?'CHECKED="CHECKED"':'';
				$checkStr = '';
				if(in_array($value['id'],$permissionKeyByUser)){
					$checkStr = 'CHECKED="CHECKED"';
				}
				else{
					$flag = false;
				}
				$resultArr[$i][] = "&nbsp;|-&nbsp;<input class=\"$class\" type=\"checkbox\" onChange=\"if($(this).is(':checked')){ajaxEditUserPermission($userId,{$value['id']},'insert');}else{ajaxEditUserPermission($userId,{$value['id']},'delete');}\" $checkStr /> {$value['key_name']}";
						
			}
			$checkStr = ($flag === true)?'CHECKED="CHECKED"':'';
			$resultArr[$k][] = "<input type=\"checkbox\" onChange=\"if($(this).is(':checked')){ajaxChooseCategory('$class','insert','$category');}else{ajaxChooseCategory('$class','delete','$category');}\" $checkStr /> <b>$category</b>";
			
			//array_reverse($resultArr[$k]);
			$i++;
		}
		ksort($resultArr);
		
		//$iTotal = $this->Key_model->get_total();
		//$iFilteredTotal = $this->Key_model->get_total($sWhere);
		$sOutput = array('sEcho'=>intval($_GET['sEcho']),
						 //'iTotalRecords'=>$iTotal,
						 //'iTotalDisplayRecords'=>$iFilteredTotal,
						 'aaData'=>$resultArr);
		
		
		echo json_encode ( $sOutput ) ;
	}
	function fnColumnToField( $i )
		{
			if ( $i == 0 )
				return "category";				
	}
	public function update_permission_user() {	
        $userId = $this->input->post('user_id');
        $method = $this->input->post('method');
        $keyId = $this->input->post('key_id');
        try {
            $this->load->model('Permission_user');
            //$method = ($this->Permission_user->getTotalRecords("user_id = $userId AND permission_key_id = $permissionKeyId")==0)?'insert':'delete';
            if($method == 'insert') {
                $this->Permission_user->insert($_POST);
            } elseif($method == 'delete') {
            	$this->Permission_user->delete_by_field(array('user_id'=>$userId,'key_id'=>$keyId));
            }
            echo json_encode(array("success" => "true","action"=>$method));
        } catch (exception $e) {
            echo json_encode(array("success" => "false","message" => $e->getMessage()));
        }
	}
	public function multi_update() {	
        $user_id = $this->input->post('user_id');
        $category = $this->input->post('category');
        $method = $this->input->post('method');
        try {
            $this->load->model('Permission_user');
            $this->load->model('Key_model');
            $tmpArr=$this->Key_model->get_by_field(array('category'=>$category),'id');
            $keyList = array();
            $data_input = array();
            foreach($tmpArr as $row){
            	$keyList[] = $row['id'];
            	$data_input[] = "($user_id,{$row['id']})";
            }
            //$method = ($this->Permission_user->getTotalRecords("user_id = $userId AND permission_key_id = $permissionKeyId")==0)?'insert':'delete';
            $result = $this->Permission_user->multi_delete($user_id,implode(',', $keyList));
            if($method == 'insert'&&$result==true) {
                $result = $this->Permission_user->multi_insert(implode(',',$data_input));
            } 
            echo json_encode(array("success" => $result,"action"=>$method));
        } catch (exception $e) {
            echo json_encode(array("success" => "false","message" => $e->getMessage()));
        }
	}
            
}
		 ?>